package com.enbatis.mybatisplugs.commons.utils;

import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TreeMap;

public class ShareDownUtil {

    public void smbGet(String remoteUrl,String localDir) {
        InputStream in = null;
        OutputStream out = null;
        try {
           SmbFile remoteFile = new SmbFile(remoteUrl);
        if(remoteFile==null){
           System.out.println("共享文件不存在");
           return;
        }
        String fileName = remoteFile.getName();
        File localFile = new File(localDir+File.separator+fileName);
        in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
        out = new BufferedOutputStream(new FileOutputStream(localFile));
        byte[] buffer = new byte[1024];
        while(in.read(buffer)!=-1){
        out.write(buffer);
        buffer = new byte[1024];
        }
        } catch (Exception e) {
        e.printStackTrace();
        } finally {
        try {
        out.close();
        in.close();
        } catch (IOException e) {
        e.printStackTrace();
        }
        }
    }


    public static void main(String[] args)  {
        //smb://xxx:xxx@192.168.2.188/testIndex/
        //xxx:xxx是共享机器的用户名密码
       String url="smb://lzjc:123456@192.168.77.28/SampleResult/";
        // String url="smb://dell:691646@192.168.77.22/Results/";
        try {
            SmbFile file = new SmbFile(url);
            if(file.exists()){
                SmbFile[] files = file.listFiles();
                for (SmbFile smbFile:files) {
                    System.out.println(smbFile.getName());
                    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(smbFile.getLastModified())));

                }


            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }


    public static SmbFile getShareFile(String  url) throws Exception {
        SmbFile file = new SmbFile(url);
        if(file.exists()){
            SmbFile[] files = file.listFiles();
            TreeMap<Long,SmbFile> fileTreeMap=new TreeMap<>();
            for (SmbFile smbFile:files) {
                fileTreeMap.put(smbFile.getLastModified(),smbFile);
            }
            if (fileTreeMap.size()>0){
               return fileTreeMap.lastEntry().getValue();
            }
        }
        return null;
    }


    public static SmbFile[] getShareFiles(String  url) throws Exception {
        SmbFile file = new SmbFile(url);
        if(file.exists()){
            SmbFile[] files = file.listFiles();
            return  files;
        }
        return null;
    }

}
